package com.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.base.BaseControllers;
import com.common.MsgReturn;
import com.model.XiaocaiAdmin;
import com.service.XiaocaiAdminService;
import com.util.JSONUtil;
import com.util.SessionUtils;
import com.util.WebConstants;
@Controller
public class AdminIndexController  extends BaseControllers{
	@Resource
	private XiaocaiAdminService xiaocaiAdminService;
	
	
	@RequestMapping({ "adminlogin" })
	public ModelAndView login(ModelMap model,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> context = new HashMap<String, Object>();
		Object adminSession = request.getSession().getAttribute(
				WebConstants.CURRENT_ADMIN);
		if (null != adminSession) {
			return forword("admin/index", context);
		}
		return forword("admin/login", context);
	}


	@RequestMapping({ "admin_login.json" })
	@ResponseBody
	public void loginForm(XiaocaiAdmin xiaocaiAdmin, String authCode,
			HttpServletRequest request, HttpServletResponse response) {
		String vcode = SessionUtils.getValidateCode(request);
		if (null != vcode && !"".equals(vcode)) {
			// 清除验证码，确保验证码只能用一次
			SessionUtils.removeValidateCode(request);
			if (StringUtils.isBlank(authCode)) {
				writerJson(response, errorMsg("验证码不能为空"));
			}
			// 判断验证码是否正确
			if (!(vcode.toLowerCase()).equals(authCode)
					&& !authCode.equals(vcode)) {
				writerJson(response, errorMsg("验证码输入错误"));
			}
		} else {
			writerJson(response, errorMsg("验证码已失效，请刷新验证码"));
		}
		xiaocaiAdmin = xiaocaiAdminService.login(xiaocaiAdmin);
		if(null!=xiaocaiAdmin&&xiaocaiAdmin.getId()>0)
	    {//登录成功
	    	writerJson(response, successMsg(xiaocaiAdmin.getAdminName()+"登录成功"));
	    	request.getSession().setAttribute(WebConstants.CURRENT_ADMIN, xiaocaiAdmin); 
	    }else
	    {//登录失败
	    	writerJson(response, JSONUtil.toJson(new MsgReturn(false,"登录失败！用户名或密码输入错误！")));
	    }
	}
}
